package cate.game.play.buff.h;

import cate.common.table.d.GDAttr;
import cate.game.attr.FightAttr;
import cate.game.play.buff.BuffHandler;
import cate.game.play.config.PlayCfgArgs;
import cate.game.play.fighter.Fighter;
import cate.game.play.proce.action.ctx.ActionCtx;
import cate.game.play.proce.action.ctx.TimeActionCtx;
import cate.game.play.proce.move.MoveCtx;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

@NoteClass("属性依赖增强BH")
public class 属性依赖增强BH extends BuffHandler {

	/** 每拥有 指定数量的 属性1  就获得指定数量的 属性2 不能超过最大值*/
	private List<Item> items = new ArrayList<>();

	@Override
	public void parse(String code) {
		if (StringUtils.isBlank(code)) {
			return;
		}
		for (String s : code.split(",")) {
			items.add(new Item(s));
		}
	}

	//检测属性=3&检测数量=100&改变属性=1&改变数量=300&基准值=0&最大值=100
	private static class Item {
		@NoteField("检测属性")
		private int checkAttr;

		@NoteField("检测数量")
		private long checkNum;

		@NoteField("改变属性")
		private int addAttr;

		@NoteField("改变数量")
		private long addNum;

		@NoteField("基准值")
		private long base;

		@NoteField("最大值")
		private long max;

		public Item(String code) {
			parse(code);
		}

		public void parse(String code) {
			PlayCfgArgs args = new PlayCfgArgs(code);
			checkAttr = args.getInt("检测属性", GDAttr.ATT);
			checkNum = args.getInt("检测数量", 1);
			addAttr = args.getInt("改变属性", GDAttr.ATT);
			addNum = args.getLong("改变数量", 1L);
			base = args.getLong("基准值", 0L);
			max = args.getLong("最大值", 0L);
		}

		@NoteField("上次计算出的增益属性")
		public FightAttr attr = new FightAttr();

		public void calAttr(Fighter f) {
			long attrValue = (long) (f.attr.getTotalValue(checkAttr) / checkNum) * addNum;
			attrValue += base;
			if (max > 0 && attrValue >= max) {
				attrValue = max;
			}
			if (attrValue <= 0) {
				attrValue = 0;
			}
			attr.clear();
			attr.add(addAttr, attrValue);
		}
	}

	@Override
	public void onAdd(ActionCtx action) {
		settle(action,true);
	}

	@Override
	public void onMoveDone(MoveCtx move, TimeActionCtx action) {
		settle(action, true);
	}

	@Override
	public void onInvalid(ActionCtx action, byte invalidReason) {
		settle(action,false);
	}

	/**
	 *
	 * @param action
	 * @param needAdd
	 */
	private void settle(ActionCtx action, boolean needAdd) {
		for (Item item : this.items) {
			buff.owner.attr.addAttr(item.attr, false, action);
			if (needAdd) {
				item.calAttr(this.buff.owner);
				buff.owner.attr.addAttr(item.attr, true, action);
			}
		}
	}
}
